package com.xrz.sxm.aj.utils;

import android.os.Environment;
import android.text.Html;
import android.util.Log;

import com.lidroid.xutils.util.LogUtils;
import com.xrz.sxm.aj.activity.R;
import com.xrz.sxm.aj.base.BaseConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class Utils {

	public static String replaceChar(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		text = text.replace("\r", "");
		text = text.replace("\\r", "");
		text = text.replace("\\\n", "");
		return Html.fromHtml(text.replace("\\n", "<br>").replace("\\", "")).toString();
	}


	/**
	 * 根据图片名字获取图片资源id
	 *
	 * @param picName
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static int getImageByPicName(String picName) {
		if (picName == null || picName.trim().equals("")) {
			return 0;
		}
		Class draw = R.mipmap.class;
		try {
			Field field = draw.getDeclaredField(picName);
			return field.getInt(picName);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 获取sd卡是否可用
	 *
	 * @return
	 */
	public static boolean isSDcardAvlive() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/*
	 * 把图片存到sdcard中
	 */
	public static String StoreImageToSDCARD(String url, String name) {
		if (isSDcardAvlive()) {
			File file = new File(BaseConfig.BASE_IMG_CACHE);
			File imagefile = new File(file, name);
			if (imagefile.exists()) {
				return imagefile.getPath();
			} else {
				try {
					if (!imagefile.exists()) {
						file.mkdirs();
						imagefile.createNewFile();
						URL ul = new URL(url);
						InputStream in = ul.openStream();
						FileOutputStream fos = new FileOutputStream(imagefile);
						int len = 0;
						byte[] buffer = new byte[1024];
						while ((len = in.read(buffer)) != -1) {
							fos.write(buffer, 0, len);
						}
						fos.close();
						in.close();
					}
					return imagefile.getPath();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		return null;
	}

	/**
	 * 检测是否是手机号
	 *
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}


	/**
	 * 发送邮件的方法
	 * @return
	 */
	public static boolean sendEmail(String content){
		Properties props = new Properties();
		props.put("mail.smtp.protocol", "smtp");
		props.put("mail.smtp.auth", "true");//设置要验证
		props.put("mail.smtp.host", "smtp.163.com");//设置host
		props.put("mail.smtp.port", "25");  //设置端口
		PassAuthenticator pass = new PassAuthenticator();   //获取帐号密码
		Session session = Session.getInstance(props, pass); //获取验证会话
		try
		{
			//配置发送及接收邮箱
			InternetAddress fromAddress, toAddress;
			/**
			 * 这个地方需要改成自己的邮箱
			 */
			fromAddress = new InternetAddress("henanailin@163.com", "自己给自己发");
			toAddress   = new InternetAddress("henanailin@163.com", "自己接收自己发的邮件");
			/**
			 * 一下内容是：发送邮件时添加附件
			 */
//			MimeBodyPart attachPart = new MimeBodyPart();
//			FileDataSource fds = new FileDataSource(Environment.getExternalStorageDirectory()+"/crash-fortrun.log"); //打开要发送的文件

//			attachPart.setDataHandler(new DataHandler(fds));
//			attachPart.setFileName(fds.getName());
//			MimeMultipart allMultipart = new MimeMultipart("mixed"); //附件
//			allMultipart.addBodyPart(attachPart);//添加
			//配置发送信息
			MimeMessage message = new MimeMessage(session);
//	            message.setContent("test", "text/plain");
//			message.setContent(allMultipart); //发邮件时添加附件
			message.setSubject(content);
			message.setFrom(fromAddress);
			message.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
			message.saveChanges();
			//连接邮箱并发送
			Transport transport = session.getTransport("smtp");
			/**
			 * 这个地方需要改称自己的账号和密码
			 */
			transport.connect("smtp.163.com", "henanailin@163.com", "aaa000000");
			transport.send(message);
			transport.close();
		} catch (Exception e) {
	        	LogUtils.e(e.toString());
		}
		return false;
	}


	/**
	 * 邮件发送程序
	 *
	 * @param host
	 *            邮件服务器 如：smtp.qq.com
	 * @param address
	 *            发送邮件的地址 如：545099227@qq.com
	 * @param from
	 *            来自： wsx2miao@qq.com
	 * @param password
	 *            您的邮箱密码
	 * @param to
	 *            接收人
	 * @param port
	 *            端口（QQ:25）
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @throws Exception
	 */
	public static void SendEmail(String host, String address, String from, String password, String to, String port, String subject, String content) throws Exception {
		Multipart multiPart;
		String finalString = "";

		Properties props = System.getProperties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", address);
		props.put("mail.smtp.password", password);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", "true");
		Log.e("Check", "done pops");
		Session session = Session.getDefaultInstance(props, null);
		DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setDataHandler(handler);
		Log.e("Check", "done sessions");

		multiPart = new MimeMultipart();
		InternetAddress toAddress;
		toAddress = new InternetAddress(to);
		message.addRecipient(Message.RecipientType.TO, toAddress);
		Log.e("Check", "added recipient");
		message.setSubject(subject);
		message.setContent(multiPart);
		message.setText(content);

		Log.e("check", "transport");
		Transport transport = session.getTransport("smtp");
		Log.e("check", "connecting");
		transport.connect(host, address, password);
		Log.e("check", "wana send");
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		Log.e("check", "sent");
	}
}
